
'''
Author: Dufolk Zhang
Date: 2021-06-27 22:06:31
LastEditTime: 2021-06-28 14:22:07
LastEditors: Please set LastEditors
Description: In User Settings Edit
FilePath: \socket\server.py
'''
import infer
import visualize
from socket import *
import time
import msvcrt
import cv2
import numpy as np
import threading
def key_wait():
    global n,decimgs
    while True:
        key = msvcrt.getch()
        if key==b'c':
            path_data = './picdata/0_'+str(n).zfill(4)+'.jpg'
            cv2.imwrite(path_data,decimgs[0])
            path_data2 = './picdata/1_'+str(n).zfill(4)+'.jpg'
            cv2.imwrite(path_data2,decimgs[1])
            n+=1
            print('save pic %s'%path_data)
            print('save pic %s'%path_data2)
        if key==b'q':
            break


def recvall(sock, count):
        buf = b''#buf是一个byte类型
        while count:
            #接受TCP套接字的数据。数据以字符串形式返回，count指定要接收的最大数据量.
            newbuf = sock.recv(count)
            if not newbuf: 
                return None
            buf += newbuf
            count -= len(newbuf)
        return buf
detector = infer.Detector(self.ModelPath, use_gpu=False, run_mode='fluid')
def predict(inputimg):
    try:
        img2=inputimg.copy()
        pred = self.self.detector.predict(img2, 0.5)
        img0 = visualize.visualize_box_mask(
            img2,
            pred,
            self.detector.config.labels,
            mask_resolution=self.detector.config.mask_resolution)
        return im0  
    except:
        pass
HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(2)
decimgs = [0,0]
threads = []
n=339
t = threading.Thread(target=key_wait)
t.setDaemon(True)
threads.append(t)
for i in threads:
    i.start()
while True:
    print('waiting for connection...')
    tcpCliSock, addr = tcpSerSock.accept()
    print('...connnecting from:', addr)
    
    while True:
        start = time.time()#用于计算帧率信息
        length = recvall(tcpCliSock,16)#获得图片文件的长度,16代表获取长度
        # print(length)
        try:
            length = int(length)
        except:
            print(length)
            continue
        
        if length % 10 == 0:
            flag = 0
        else:
            flag = 1
        length = (length - flag) / 10
        stringData = recvall(tcpCliSock, int(length))#根据获得的文件长度，获取图片文件
        data = np.frombuffer(stringData, np.uint8)#将获取到的字符流数据转换成1维数组
        img=cv2.imdecode(data,cv2.IMREAD_COLOR)#将数组解码成图像
        
        # img = cv2.resize(img,(600,400))
        #print(decimg)
        #cv2.imshow('SERVER',decimg)#显示图像
        decimgs[flag] = img
            
        end = time.time()
        seconds = end - start
        try:
            fps  = 'FPS:'+str(int(1/seconds))
        except:
            pass
        # cv2.putText(decimg, fps, (0, 15), cv2.FONT_HERSHEY_COMPLEX, 0.7, (0, 255, 0), 1)
        
        try:
            out1=predict(decimgs[0])
            out2=predict(decimgs[1])
            cv2.imshow("recv1",out1)
            cv2.imshow("recv2",out2)
        except:
            pass
        cv2.waitKey(1)
    tcpCliSock.close()
tcpSerSock.close()
